package com.kk.xhr.admin.biz.impl;

import com.kk.xhr.admin.biz.IPositionBizService;
import com.kk.xhr.admin.controller.vo.PositionVO;
import com.kk.xhr.common.ErrorCodeEnum;
import com.kk.xhr.common.exception.BusinessException;
import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.dto.PositionDTO;
import com.kk.xhr.model.service.IPositionService;
import com.kk.xhr.model.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 职位biz服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/5
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
public class PositionBizServiceImpl implements IPositionBizService {
    private final IPositionService positionService;
    private final IUserService userService;

    /**
     * {@inheritDoc}
     */
    @Override
    public List<PositionVO> query() {
        List<PositionDTO> list = positionService.query();
        if (0 == list.size()) {
            return Collections.emptyList();
        }
        return list.stream().map(dto -> PositionVO.builder()
            .id(dto.getId())
            .name(dto.getName())
            .status(dto.getStatus())
            .build())
            .collect(Collectors.toList());
    }

    @Override
    public boolean add(String name) {
        if (positionService.existName(name)) {
            throw new BusinessException(ErrorCodeEnum.POSITION_ALREADY_EXIST);
        }
        return positionService.add(PositionDTO.builder()
            .name(name)
            .build());
    }

    @Override
    public boolean modify(Long id, String name) {
        if (!positionService.queryById(id).isPresent()) {
            throw new BusinessException(ErrorCodeEnum.POSITION_NOT_EXIST);
        }
        return positionService.modify(PositionDTO.builder()
            .id(id)
            .name(name)
            .build());
    }

    @Override
    public boolean modifyStatus(Long id, BinaryEnum status) {
        Optional<PositionDTO> optional = positionService.queryById(id);
        if (!optional.isPresent()) {
            throw new BusinessException(ErrorCodeEnum.POSITION_NOT_EXIST);
        }
        if (optional.get().getStatus() == status) {
            return true;
        }
        if (BinaryEnum.FALSE == status) {
            if (userService.existPosition(id)) {
                throw new BusinessException(ErrorCodeEnum.POSITION_DELETE_FAIL);
            }
        }
        return positionService.modifyStatus(id, status);
    }
}
